from rest_framework import serializers
from .models import User

class UserRegisterSerializer(serializers.ModelSerializer):
    """用户注册序列化器"""
    confirm_password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = ['username', 'password', 'confirm_password', 'email', 'phone', 'identity']
        extra_kwargs = {
            'password': {
                'write_only': True,
                'style': {'input_type': 'password'}
            },
            'username': {'required': True},
            'email': {'required': True},
            'phone': {'required': True},
            'identity': {'required': True}
        }

    def validate(self, data):
        """验证两次密码是否一致"""
        if data['password'] != data['confirm_password']:
            raise serializers.ValidationError({
                'confirm_password': '两次密码不一致'
            })
        return data

    def create(self, validated_data):
        """创建用户时正确处理密码"""
        validated_data.pop('confirm_password')
        user = User.objects.create_user(**validated_data)
        return user

class UserInfoSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    identity_display = serializers.CharField(source='get_identity_display', read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'phone', 'identity', 
                 'identity_display', 'is_superuser', 'created_at']
